package config

import "epg-mc/database"

//some config keys.
var (
	SiteTitle         = "site_title"
	ConsulAddr        = "consul_addr"
	ConsulAdminKey    = "consul_admin_key"
	ConsulEpgEditKey  = "consul_epg_edit_key"
	ConsulEpgViewKey  = "consul_epg_view_key"
	GrafanaSysMetrics = "grafana_sysmetrics"
	GrafanaEPGProxy   = "grafana_epgproxy"
	SlowQueryAPI      = "slow_query_api"
	ErrorLogAPI       = "error_log_api"
	NodeHostsAPI      = "node_hosts_api"
	DataCenters       = "datacenters"
	DBPrivAPI         = "db_priv_key"
)

//Config all the config save in the sqlite3
type Config struct {
	ID      int `gorm:"primary_key"`
	Group   string
	Key     string `gorm:"not null;unique"`
	Value   string
	Comment string
}

var (
	db = database.ORM
)

//GetAll find all config.
func GetAll() []Config {
	confs := make([]Config, 0, 32)
	db.Find(&confs)
	return confs
}

//FindByKey find one config by key.
func FindByKey(k string) *Config {
	conf := &Config{}
	db.First(conf, "key= ?", k)
	return conf
}

//GetValue get the value of key.
func GetValue(k string) string {
	conf := &Config{}
	db.First(conf, "key= ?", k)
	return conf.Value
}

//Update update the key val.
func Update(key string, val string) bool {
	db.Model(&Config{}).Where("key = ?", key).Update("value", val)
	return true
}

func Save(c *Config) error {
	d := db.Model(&Config{}).Save(c)
	if d.Error != nil {
		return d.Error
	}
	return nil
}

func Delete(key string) error {
	db.Delete(&Config{}, "key = ?", key)
	return db.Error
}
